<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/greenwood.gitee.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/greenwood.gitee.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/greenwood.gitee.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/greenwood.gitee.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/greenwood.gitee.io/css/main.css">


<link rel="stylesheet" href="/greenwood.gitee.io/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/greenwood.gitee.io/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="基础1.1 类和接口 继承Thread，重写run方法，调用start">
<meta property="og:type" content="article">
<meta property="og:title" content="JAVA多线程第一章">
<meta property="og:url" content="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/09/28/%E5%A4%9A%E7%BA%BF%E7%A8%8Bchap1/index.html">
<meta property="og:site_name" content="我看刑">
<meta property="og:description" content="基础1.1 类和接口 继承Thread，重写run方法，调用start">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-28T13:38:53.445Z">
<meta property="article:modified_time" content="2021-09-28T16:35:47.191Z">
<meta property="article:author" content="Dybala">
<meta property="article:tag" content="JAVA">
<meta property="article:tag" content="并发">
<meta property="article:tag" content="多线程">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/09/28/%E5%A4%9A%E7%BA%BF%E7%A8%8Bchap1/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>JAVA多线程第一章 | 我看刑</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/greenwood.gitee.io/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">我看刑</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/greenwood.gitee.io/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/greenwood.gitee.io/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/greenwood.gitee.io/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/greenwood.gitee.io/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/greenwood.gitee.io/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/09/28/%E5%A4%9A%E7%BA%BF%E7%A8%8Bchap1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/greenwood.gitee.io/images/avatar.gif">
      <meta itemprop="name" content="Dybala">
      <meta itemprop="description" content="日子越来越有判头了">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我看刑">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JAVA多线程第一章
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-09-28 21:38:53" itemprop="dateCreated datePublished" datetime="2021-09-28T21:38:53+08:00">2021-09-28</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-09-29 00:35:47" itemprop="dateModified" datetime="2021-09-29T00:35:47+08:00">2021-09-29</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/greenwood.gitee.io/categories/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" itemprop="url" rel="index"><span itemprop="name">多线程</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="基础"><a href="#基础" class="headerlink" title="基础"></a>基础</h1><h2 id="1-1-类和接口"><a href="#1-1-类和接口" class="headerlink" title="1.1 类和接口"></a>1.1 类和接口</h2><ul>
<li>继承Thread，重写run方法，调用start<span id="more"></span>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BaseOp</span> <span class="keyword">extends</span> <span class="title">Thread</span></span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;test for concurrency!!!&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Thread test=<span class="keyword">new</span> BaseOp();</span><br><span class="line">        test.start();</span><br><span class="line">        System.out.println(<span class="string">&quot;over&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>我们在程序里面调用了start()方法后，虚拟机会先为我们创建一个线程，然后等到这个线程第一次得到时间片时再调用run()方法。</li>
<li>注意不可多次调用start()方法。在第一次调用start()方法后，再次调用start()方法会抛出IllegalThreadStateException异常。</li>
</ul>
<h2 id="1-2-几个常用方法"><a href="#1-2-几个常用方法" class="headerlink" title="1.2 几个常用方法"></a>1.2 几个常用方法</h2><ol>
<li>currentThread()：静态方法，返回对当前正在执行的线程对象的引用；</li>
<li>start()：开始执行线程的方法，java虚拟机会调用线程内的run()方法；</li>
<li>yield()：yield在英语里有放弃的意思，同样，这里的yield()指的是当前线程愿意让出对当前处理器的占用。这里需要注意的是，就算当前线程调用了yield()方法，程序在调度的时候，也还有可能继续运行这个线程的；</li>
<li>sleep()：静态方法，使当前线程睡眠一段时间；</li>
<li>join()：使当前线程等待另一个线程执行完毕之后再继续执行，内部调用的是Object类的wait方法实现的；</li>
</ol>
<h1 id="2-线程组"><a href="#2-线程组" class="headerlink" title="2. 线程组"></a>2. 线程组</h1><h2 id="2-1-线程组和线程"><a href="#2-1-线程组和线程" class="headerlink" title="2.1 线程组和线程"></a>2.1 线程组和线程</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">       ThreadGroup threadGroup = <span class="keyword">new</span> ThreadGroup(<span class="string">&quot;t1&quot;</span>);</span><br><span class="line">       threadGroup.setMaxPriority(<span class="number">6</span>);</span><br><span class="line">       Thread thread = <span class="keyword">new</span> Thread(threadGroup,<span class="string">&quot;thread&quot;</span>);</span><br><span class="line">       thread.setPriority(<span class="number">9</span>);</span><br><span class="line">       System.out.println(<span class="string">&quot;线程组的优先级&quot;</span>+threadGroup.getMaxPriority());</span><br><span class="line">       System.out.println(<span class="string">&quot;线程的优先级&quot;</span>+thread.getPriority());</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>如果某个线程优先级大于线程所在线程组的最大优先级，那么该线程的优先级将会失效，取而代之的是线程组的最大优先级。<h2 id="2-2-常用方法"><a href="#2-2-常用方法" class="headerlink" title="2.2 常用方法"></a>2.2 常用方法</h2></li>
</ul>
<ol>
<li>获取当前线程组的名字<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Thread.currentThread().getThreadGroup().getName()</span><br></pre></td></tr></table></figure></li>
<li>复制线程组,把线程组转化成线程数组<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取当前的线程组</span></span><br><span class="line">ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();</span><br><span class="line"><span class="comment">// 复制一个线程组到一个线程数组（获取Thread信息）</span></span><br><span class="line">Thread[] threads = <span class="keyword">new</span> Thread[threadGroup.activeCount()];</span><br><span class="line"><span class="comment">// 复制</span></span><br><span class="line">threadGroup.enumerate(threads);</span><br></pre></td></tr></table></figure>
<h2 id="2-3-数据结构"><a href="#2-3-数据结构" class="headerlink" title="2.3 数据结构"></a>2.3 数据结构</h2>线程组中可以包含其他线程组。<br>给出ThreadGroup源码中的成员变量<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadGroup</span> <span class="keyword">implements</span> <span class="title">Thread</span>.<span class="title">UncaughtExceptionHandler</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ThreadGroup parent; <span class="comment">// 父亲ThreadGroup</span></span><br><span class="line">    String name; <span class="comment">// ThreadGroupr 的名称</span></span><br><span class="line">    <span class="keyword">int</span> maxPriority; <span class="comment">// 线程最大优先级</span></span><br><span class="line">    <span class="keyword">boolean</span> destroyed; <span class="comment">// 是否被销毁</span></span><br><span class="line">    <span class="keyword">boolean</span> daemon; <span class="comment">// 是否守护线程</span></span><br><span class="line">    <span class="keyword">boolean</span> vmAllowSuspension; <span class="comment">// 是否可以中断</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> nUnstartedThreads = <span class="number">0</span>; <span class="comment">// 还未启动的线程</span></span><br><span class="line">    <span class="keyword">int</span> nthreads; <span class="comment">// ThreadGroup中线程数目</span></span><br><span class="line">    Thread threads[]; <span class="comment">// ThreadGroup中的线程</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> ngroups; <span class="comment">// 线程组数目</span></span><br><span class="line">    ThreadGroup groups[]; <span class="comment">// 线程组数组</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="3-线程的状态和转换方法"><a href="#3-线程的状态和转换方法" class="headerlink" title="3. 线程的状态和转换方法"></a>3. 线程的状态和转换方法</h1><h2 id="3-1-Java线程的六个状态"><a href="#3-1-Java线程的六个状态" class="headerlink" title="3.1 Java线程的六个状态"></a>3.1 Java线程的六个状态</h2><h3 id="3-1-0-状态源码"><a href="#3-1-0-状态源码" class="headerlink" title="3.1.0 状态源码"></a>3.1.0 状态源码</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Thread.State 源码</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">enum</span> <span class="title">State</span> </span>&#123;</span><br><span class="line">    NEW,</span><br><span class="line">    RUNNABLE,</span><br><span class="line">    BLOCKED,</span><br><span class="line">    WAITING,</span><br><span class="line">    TIMED_WAITING,</span><br><span class="line">    TERMINATED;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-1-1-NEW状态"><a href="#3-1-1-NEW状态" class="headerlink" title="3.1.1 NEW状态"></a>3.1.1 NEW状态</h3></li>
</ol>
<ul>
<li>处于NEW状态的线程此时尚未启动。这里的尚未启动指的是还没调用Thread实例的start()方法。</li>
</ul>
<p>关于start()的两个引申问题：</p>
<ol>
<li>是否可以反复调用同一个线程的start</li>
<li>线程执行完毕后，能否再次使用start激活该线程<br>首先我们要分析start的源码<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (threadStatus != <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalThreadStateException();</span><br><span class="line"><span class="comment">//表明threadStatus不为0直接抛出异常</span></span><br><span class="line">    group.add(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">boolean</span> started = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        start0();</span><br><span class="line">        started = <span class="keyword">true</span>;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (!started) &#123;</span><br><span class="line">                group.threadStartFailed(<span class="keyword">this</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable ignore) &#123;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>查看当前线程状态的源码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Thread.getState方法源码：</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> State <span class="title">getState</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// get current thread state</span></span><br><span class="line">    <span class="keyword">return</span> sun.misc.VM.toThreadState(threadStatus);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// sun.misc.VM 源码：</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> State <span class="title">toThreadState</span><span class="params">(<span class="keyword">int</span> var0)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> ((var0 &amp; <span class="number">4</span>) != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> State.RUNNABLE;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> ((var0 &amp; <span class="number">1024</span>) != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> State.BLOCKED;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> ((var0 &amp; <span class="number">16</span>) != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> State.WAITING;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> ((var0 &amp; <span class="number">32</span>) != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> State.TIMED_WAITING;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> ((var0 &amp; <span class="number">2</span>) != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> State.TERMINATED;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> (var0 &amp; <span class="number">1</span>) == <span class="number">0</span> ? State.NEW : State.RUNNABLE;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因此回答上面两个问题，都是不可以的，第一次调用start后，threadStatus的值会变化，抛出异常，比如threadStatus=2代表当前状态为TERMINATED</p>
<h3 id="3-1-2-RUNNABLE状态"><a href="#3-1-2-RUNNABLE状态" class="headerlink" title="3.1.2 RUNNABLE状态"></a>3.1.2 RUNNABLE状态</h3><p>表示当前线程正在运行中。处于RUNNABLE状态的线程在Java虚拟机中运行，也有可能在等待CPU分配资源。<br>在java里面，RUNNABLE状态其实包括了传统OS线程的ready和running状态。</p>
<h3 id="3-1-3-BLOCKED状态"><a href="#3-1-3-BLOCKED状态" class="headerlink" title="3.1.3 BLOCKED状态"></a>3.1.3 BLOCKED状态</h3><p>阻塞状态。处于BLOCKED状态的线程正等待锁的释放以进入同步区。</p>
<h3 id="3-1-4-WAITING状态"><a href="#3-1-4-WAITING状态" class="headerlink" title="3.1.4 WAITING状态"></a>3.1.4 WAITING状态</h3><p>等待状态。处于等待状态的线程变成RUNNABLE状态需要其他线程唤醒。<br>调用以下三个方法会使线程进入等待状态。</p>
<ul>
<li>Object.wait() 使当前线程处于等待状态直到另一个线程唤醒它</li>
<li>Thread.join() 等待线程执行完毕，底层调用的wait方法</li>
<li>LockSupport.park() 除非获得许可，否则禁止当前线程进行线程调度</li>
</ul>
<h3 id="3-1-5-TIMED-WAITING"><a href="#3-1-5-TIMED-WAITING" class="headerlink" title="3.1.5 TIMED_WAITING"></a>3.1.5 TIMED_WAITING</h3><p>超时等待状态。线程等待一个具体的时间，时间到后会被自动唤醒。</p>
<h3 id="3-1-6-TERMINATED"><a href="#3-1-6-TERMINATED" class="headerlink" title="3.1.6 TERMINATED"></a>3.1.6 TERMINATED</h3><p>终止状态，表明线程已经执行完毕。</p>
<h2 id="3-2-线程状态之间的相互转换"><a href="#3-2-线程状态之间的相互转换" class="headerlink" title="3.2 线程状态之间的相互转换"></a>3.2 线程状态之间的相互转换</h2><h3 id="3-2-1-BLOCKED和RUNNABLE之间的转换"><a href="#3-2-1-BLOCKED和RUNNABLE之间的转换" class="headerlink" title="3.2.1 BLOCKED和RUNNABLE之间的转换"></a>3.2.1 BLOCKED和RUNNABLE之间的转换</h3><p>释放资源锁即可</p>
<h3 id="3-2-2-WATING和RUNNABLE状态的转换"><a href="#3-2-2-WATING和RUNNABLE状态的转换" class="headerlink" title="3.2.2 WATING和RUNNABLE状态的转换"></a>3.2.2 WATING和RUNNABLE状态的转换</h3><p>有三种方法可以进入waiting状态，主要看下wait和join方法<br>Object.wait()<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">调用wait()方法前线程必须持有对象的锁。</span><br><span class="line"></span><br><span class="line">线程调用wait()方法时，会释放当前的锁，直到有其他线程调用notify()/notifyAll()方法唤醒等待锁的线程。</span><br><span class="line"></span><br><span class="line">需要注意的是，其他线程调用notify()方法只会唤醒单个等待锁的线程，如有有多个线程都在等待这个锁的话不一定会唤醒到之前调用wait()方法的线程。</span><br><span class="line"></span><br><span class="line">同样，调用notifyAll()方法唤醒所有等待锁的线程之后，也不一定会马上把时间片分给刚才放弃锁的那个线程，具体要看系统的调度。</span><br></pre></td></tr></table></figure></p>
<p>Thread.join()<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">调用join()方法，其他线程会一直等待这个线程执行完毕（转换为TERMINATED状态）。</span><br><span class="line">相当于直接抢占CPU资源</span><br></pre></td></tr></table></figure></p>
<h3 id="3-2-3-TIMED-WAITING与RUNNABLE状态转换"><a href="#3-2-3-TIMED-WAITING与RUNNABLE状态转换" class="headerlink" title="3.2.3 TIMED_WAITING与RUNNABLE状态转换"></a>3.2.3 TIMED_WAITING与RUNNABLE状态转换</h3><p>TIMED_WAITING与WAITING状态类似，只是TIMED_WAITING状态等待的时间是指定的。<br>Thread.sleep(long)<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">使当前线程睡眠指定时间。需要注意这里的“睡眠”只是暂时使线程停止执行，并不会释放锁。时间到后，线程会重新进入RUNNABLE状态。</span><br></pre></td></tr></table></figure><br>Object.wait(long)<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">wait(long)方法使线程进入TIMED_WAITING状态。这里的wait(long)方法与无参方法wait()相同的地方是，都可以通过其他线程调用notify()或notifyAll()方法来唤醒。</span><br><span class="line"></span><br><span class="line">不同的地方是，有参方法wait(long)就算其他线程不来唤醒它，经过指定时间long之后它会自动唤醒，拥有去争夺锁的资格。</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure></p>
<p>Thread.join(long)<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">join(long)使当前线程执行指定时间，并且使线程进入TIMED_WAITING状态。</span><br></pre></td></tr></table></figure></p>
<h1 id="4-线程之间的通信"><a href="#4-线程之间的通信" class="headerlink" title="4 线程之间的通信"></a>4 线程之间的通信</h1><h2 id="4-1-锁和同步"><a href="#4-1-锁和同步" class="headerlink" title="4.1 锁和同步"></a>4.1 锁和同步</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.dybala.chap1;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ObjectLock</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Object lock = <span class="keyword">new</span> Object();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadA</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">                    System.out.println(<span class="string">&quot;Thread A &quot;</span> + i);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadB</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">                    System.out.println(<span class="string">&quot;Thread B &quot;</span> + i);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> Thread(<span class="keyword">new</span> ThreadA()).start();</span><br><span class="line">        Thread.sleep(<span class="number">10</span>);</span><br><span class="line">        <span class="keyword">new</span> Thread(<span class="keyword">new</span> ThreadB()).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>用<strong>synchronized</strong>关键字加上了同一个对象锁lock。</p>
<h2 id="4-2-等待-通知机制"><a href="#4-2-等待-通知机制" class="headerlink" title="4.2 等待/通知机制"></a>4.2 等待/通知机制</h2><p>在基于<strong>锁</strong>的机制中，线程需要不断取尝试获得锁，处于忙等状态。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Java多线程的等待/通知机制是基于Object类的wait()方法和notify(), notifyAll()方法来实现的。</span><br><span class="line">notify()方法会 随机 叫醒一个正在等待的线程，而notifyAll()会叫醒所有正在等待的线程。</span><br></pre></td></tr></table></figure>
<p>假如线程A现在持有了一个锁lock并开始执行，它可以使用lock.wait()让自己进入等待状态。这个时候，lock这个锁是被释放了的。</p>
<p>这时，线程B获得了lock这个锁并开始执行，它可以在某一时刻，使用lock.notify()，通知之前持有lock锁并进入等待状态的线程A，说“线程A你不用等了，可以往下执行了”。<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">需要注意的是，这个时候线程B并没有释放锁lock，除非线程B这个时候使用lock.wait()释放锁，或者线程B执行结束自行释放锁，线程A才能得到lock锁。</span><br></pre></td></tr></table></figure></p>
<p>代码模拟：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.dybala.chap1;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WaitAndNotify</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Object lock = <span class="keyword">new</span> Object();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadA</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        System.out.println(<span class="string">&quot;ThreadA: &quot;</span> + i);</span><br><span class="line">                        lock.notify();</span><br><span class="line">                        lock.wait();</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                lock.notify();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadB</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        System.out.println(<span class="string">&quot;ThreadB: &quot;</span> + i);</span><br><span class="line">                        lock.notify();</span><br><span class="line">                        lock.wait();</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                lock.notify();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> Thread(<span class="keyword">new</span> ThreadA()).start();</span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        <span class="keyword">new</span> Thread(<span class="keyword">new</span> ThreadB()).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>线程A和线程B首先打印出自己需要的东西，然后使用notify()方法叫醒另一个正在等待的线程，然后自己使用wait()方法陷入等待并释放lock锁。</p>
<h2 id="4-3-信号量"><a href="#4-3-信号量" class="headerlink" title="4.3 信号量"></a>4.3 信号量</h2><p>volatile关键字：<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">volatile关键字能够保证内存的可见性，如果用volatile关键字声明了一个变量，在一个线程里面改变了这个变量的值，那其它线程是立马可见更改后的值的</span><br></pre></td></tr></table></figure><br>相当于同步更改变量的值</p>
<h2 id="4-4-管道"><a href="#4-4-管道" class="headerlink" title="4.4 管道"></a>4.4 管道</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Pipe</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ReaderThread</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> PipedReader reader;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">ReaderThread</span><span class="params">(PipedReader reader)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.reader = reader;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;this is reader&quot;</span>);</span><br><span class="line">            <span class="keyword">int</span> receive = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">while</span> ((receive = reader.read()) != -<span class="number">1</span>) &#123;</span><br><span class="line">                    System.out.print((<span class="keyword">char</span>)receive);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">WriterThread</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> PipedWriter writer;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">WriterThread</span><span class="params">(PipedWriter writer)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.writer = writer;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;this is writer&quot;</span>);</span><br><span class="line">            <span class="keyword">int</span> receive = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                writer.write(<span class="string">&quot;test&quot;</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    writer.close();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, InterruptedException </span>&#123;</span><br><span class="line">        PipedWriter writer = <span class="keyword">new</span> PipedWriter();</span><br><span class="line">        PipedReader reader = <span class="keyword">new</span> PipedReader();</span><br><span class="line">        writer.connect(reader); <span class="comment">// 这里注意一定要连接，才能通信</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> Thread(<span class="keyword">new</span> ReaderThread(reader)).start();</span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        <span class="keyword">new</span> Thread(<span class="keyword">new</span> WriterThread(writer)).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出：</span></span><br><span class="line"><span class="keyword">this</span> is reader</span><br><span class="line"><span class="keyword">this</span> is writer</span><br><span class="line">test</span><br></pre></td></tr></table></figure>
<h2 id="4-5-其他方法"><a href="#4-5-其他方法" class="headerlink" title="4.5 其他方法"></a>4.5 其他方法</h2><h3 id="4-5-1-join方法"><a href="#4-5-1-join方法" class="headerlink" title="4.5.1 join方法"></a>4.5.1 join方法</h3><h3 id="4-5-2-sleep方法"><a href="#4-5-2-sleep方法" class="headerlink" title="4.5.2 sleep方法"></a>4.5.2 sleep方法</h3><h3 id="4-5-3-ThreadLocal类"><a href="#4-5-3-ThreadLocal类" class="headerlink" title="4.5.3 ThreadLocal类"></a>4.5.3 ThreadLocal类</h3><h3 id="4-5-4-Inheritable-ThreadLocal"><a href="#4-5-4-Inheritable-ThreadLocal" class="headerlink" title="4.5.4 Inheritable ThreadLocal"></a>4.5.4 Inheritable ThreadLocal</h3><p>InheritableThreadLocal类与ThreadLocal类稍有不同，Inheritable是继承的意思。它不仅仅是当前线程可以存取副本值，而且它的子线程也可以存取这个副本值。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/greenwood.gitee.io/tags/JAVA/" rel="tag"># JAVA</a>
              <a href="/greenwood.gitee.io/tags/%E5%B9%B6%E5%8F%91/" rel="tag"># 并发</a>
              <a href="/greenwood.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag"># 多线程</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/greenwood.gitee.io/2021/09/28/hello-world/" rel="prev" title="Hello World">
      <i class="fa fa-chevron-left"></i> Hello World
    </a></div>
      <div class="post-nav-item">
    <a href="/greenwood.gitee.io/2021/09/29/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E4%B8%83%E5%A4%A7%E8%BD%AF%E4%BB%B6%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99/" rel="next" title="JAVA设计模式第一章">
      JAVA设计模式第一章 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9F%BA%E7%A1%80"><span class="nav-number">1.</span> <span class="nav-text">基础</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-%E7%B1%BB%E5%92%8C%E6%8E%A5%E5%8F%A3"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 类和接口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-%E5%87%A0%E4%B8%AA%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 几个常用方法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-%E7%BA%BF%E7%A8%8B%E7%BB%84"><span class="nav-number">2.</span> <span class="nav-text">2. 线程组</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-%E7%BA%BF%E7%A8%8B%E7%BB%84%E5%92%8C%E7%BA%BF%E7%A8%8B"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 线程组和线程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 常用方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 数据结构</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-%E7%BA%BF%E7%A8%8B%E7%9A%84%E7%8A%B6%E6%80%81%E5%92%8C%E8%BD%AC%E6%8D%A2%E6%96%B9%E6%B3%95"><span class="nav-number">3.</span> <span class="nav-text">3. 线程的状态和转换方法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-Java%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%85%AD%E4%B8%AA%E7%8A%B6%E6%80%81"><span class="nav-number">3.1.</span> <span class="nav-text">3.1 Java线程的六个状态</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-0-%E7%8A%B6%E6%80%81%E6%BA%90%E7%A0%81"><span class="nav-number">3.1.1.</span> <span class="nav-text">3.1.0 状态源码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-1-NEW%E7%8A%B6%E6%80%81"><span class="nav-number">3.1.2.</span> <span class="nav-text">3.1.1 NEW状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-2-RUNNABLE%E7%8A%B6%E6%80%81"><span class="nav-number">3.1.3.</span> <span class="nav-text">3.1.2 RUNNABLE状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-3-BLOCKED%E7%8A%B6%E6%80%81"><span class="nav-number">3.1.4.</span> <span class="nav-text">3.1.3 BLOCKED状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-4-WAITING%E7%8A%B6%E6%80%81"><span class="nav-number">3.1.5.</span> <span class="nav-text">3.1.4 WAITING状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-5-TIMED-WAITING"><span class="nav-number">3.1.6.</span> <span class="nav-text">3.1.5 TIMED_WAITING</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-6-TERMINATED"><span class="nav-number">3.1.7.</span> <span class="nav-text">3.1.6 TERMINATED</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81%E4%B9%8B%E9%97%B4%E7%9A%84%E7%9B%B8%E4%BA%92%E8%BD%AC%E6%8D%A2"><span class="nav-number">3.2.</span> <span class="nav-text">3.2 线程状态之间的相互转换</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-1-BLOCKED%E5%92%8CRUNNABLE%E4%B9%8B%E9%97%B4%E7%9A%84%E8%BD%AC%E6%8D%A2"><span class="nav-number">3.2.1.</span> <span class="nav-text">3.2.1 BLOCKED和RUNNABLE之间的转换</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-2-WATING%E5%92%8CRUNNABLE%E7%8A%B6%E6%80%81%E7%9A%84%E8%BD%AC%E6%8D%A2"><span class="nav-number">3.2.2.</span> <span class="nav-text">3.2.2 WATING和RUNNABLE状态的转换</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-3-TIMED-WAITING%E4%B8%8ERUNNABLE%E7%8A%B6%E6%80%81%E8%BD%AC%E6%8D%A2"><span class="nav-number">3.2.3.</span> <span class="nav-text">3.2.3 TIMED_WAITING与RUNNABLE状态转换</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-%E7%BA%BF%E7%A8%8B%E4%B9%8B%E9%97%B4%E7%9A%84%E9%80%9A%E4%BF%A1"><span class="nav-number">4.</span> <span class="nav-text">4 线程之间的通信</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-%E9%94%81%E5%92%8C%E5%90%8C%E6%AD%A5"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 锁和同步</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-%E7%AD%89%E5%BE%85-%E9%80%9A%E7%9F%A5%E6%9C%BA%E5%88%B6"><span class="nav-number">4.2.</span> <span class="nav-text">4.2 等待&#x2F;通知机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-%E4%BF%A1%E5%8F%B7%E9%87%8F"><span class="nav-number">4.3.</span> <span class="nav-text">4.3 信号量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-4-%E7%AE%A1%E9%81%93"><span class="nav-number">4.4.</span> <span class="nav-text">4.4 管道</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-5-%E5%85%B6%E4%BB%96%E6%96%B9%E6%B3%95"><span class="nav-number">4.5.</span> <span class="nav-text">4.5 其他方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-5-1-join%E6%96%B9%E6%B3%95"><span class="nav-number">4.5.1.</span> <span class="nav-text">4.5.1 join方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-5-2-sleep%E6%96%B9%E6%B3%95"><span class="nav-number">4.5.2.</span> <span class="nav-text">4.5.2 sleep方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-5-3-ThreadLocal%E7%B1%BB"><span class="nav-number">4.5.3.</span> <span class="nav-text">4.5.3 ThreadLocal类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-5-4-Inheritable-ThreadLocal"><span class="nav-number">4.5.4.</span> <span class="nav-text">4.5.4 Inheritable ThreadLocal</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Dybala</p>
  <div class="site-description" itemprop="description">日子越来越有判头了</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/greenwood.gitee.io/archives/">
        
          <span class="site-state-item-count">22</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/greenwood.gitee.io/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/greenwood.gitee.io/tags/">
          
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Dybala</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/greenwood.gitee.io/lib/anime.min.js"></script>
  <script src="/greenwood.gitee.io/lib/velocity/velocity.min.js"></script>
  <script src="/greenwood.gitee.io/lib/velocity/velocity.ui.min.js"></script>

<script src="/greenwood.gitee.io/js/utils.js"></script>

<script src="/greenwood.gitee.io/js/motion.js"></script>


<script src="/greenwood.gitee.io/js/schemes/pisces.js"></script>


<script src="/greenwood.gitee.io/js/next-boot.js"></script>




  















  

  

  

</body>
</html>
